package org.example.blogger.utils;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

public class SecurityUtils {
    public static String encrypt(String password){
        //产生随机盐值
        String salt = UUID.randomUUID().toString().replace("-","");
        //对 明文+盐值 进行MD5加密
        String finalPassword = DigestUtils.md5DigestAsHex((password+salt).getBytes());
        return salt + finalPassword;
    }

    public static boolean verify(String inputPassword,String sqlPassword){
        if (!StringUtils.hasLength(inputPassword)) {
            return  false;
        }
        if (sqlPassword == null || sqlPassword.length() != 64){
            return  false;
        }
        //从数据库中获取盐值
        String salt = sqlPassword.substring(0,32);

        String finalPassword = DigestUtils.md5DigestAsHex((inputPassword+salt).getBytes());
        return (salt + finalPassword ).equals(sqlPassword);
    }

}
